package com.splant.android.smart.UILevel.Community.fragments;


import android.app.Fragment;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.splant.android.R;
import com.splant.android.smart.CommunicationLevel.sPlantAsyncHttpClient;
import com.splant.android.smart.CommunicationLevel.sPlantJsonHttpResponseHandler;
import com.splant.android.smart.Global;
import com.splant.android.smart.ModelLevel.AreaListBean;
import com.splant.android.smart.ModelLevel.WaterListBean;
import com.splant.android.smart.ModelLevel.event.PostWater;
import com.splant.android.smart.SystemDefinedLevel.Utils.System_Dimen_Util;
import com.splant.android.smart.UILevel.Community.Garden_Water_Activity;
import org.apache.http.Header;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

public class Garden_WaterList_Fragment extends Fragment {

    private static  int REQUEST_COUNT =8;
    private String areaId="";
    public void selectArea() {

        if (tv_areaName!=null)
        {
            String curAreaName=tv_areaName.getText().toString();
            if (Global.selectedArea!=null&&curAreaName.equals("选择区域")==false&&Global.selectedArea.getAreaId().equals(areaId)==false)
            {
                pageNo=0;
                waterList.clear();
                lrv_waterList.setNoMore(false);
                getDatas();
            }
        }
        if (Global.selectedArea!=null&&Global.selectedArea.getAreaId().equals(""))
        {
            lrv_waterList.setLoadMoreEnabled(true);
        }
    }

    private sPlantAsyncHttpClient sPlantClient;
    private View mView;
    private LRecyclerView lrv_waterList;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private Garden_WaterList_Adapter garden_waterList_adapter;
    private List<WaterListBean.Water> waterList = new ArrayList<>();
    private TextView tv_areaName;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mView == null) {

            mView = inflater.inflate(R.layout.garden_waterlist_fragment, null);

            lrv_waterList = (LRecyclerView) mView.findViewById(R.id.lrv_waterList);

            tv_areaName= (TextView) getActivity().findViewById(R.id.tv_areaName);

            sPlantClient = sPlantAsyncHttpClient.getInstance();

            init();

            EventBus.getDefault().register(this);
        }
        return mView;
    }
    private void init()
    {
        garden_waterList_adapter = new Garden_WaterList_Adapter(getActivity());
        lRecyclerViewAdapter = new LRecyclerViewAdapter(garden_waterList_adapter);

        lrv_waterList.setHasFixedSize(true);
        lrv_waterList.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        lrv_waterList.setAdapter(lRecyclerViewAdapter);
        lrv_waterList.setRefreshProgressStyle(ProgressStyle.BallClipRotateMultiple);

        GridItemDecoration divider = new GridItemDecoration.Builder(getActivity())
                    .setVertical(R.dimen.gaiaa_devicelist_dh)
                .setColorResource(R.color.garden_color0)
                .build();

        lrv_waterList.addItemDecoration(divider);

        lrv_waterList.setFooterViewHint("拼命加载中","已经全部为你呈现了","网络不给力啊，点击再试一次吧");
        lrv_waterList.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);

        lrv_waterList.setOnRefreshListener(onRefreshListener);

        lrv_waterList.setOnLoadMoreListener(onLoadMoreListener);

        garden_waterList_adapter.setOnItemClickListener(new Garden_WaterList_Adapter.onItemClickListener() {
            @Override
            public void onItemChick(int pos) {
                selectIndex=pos;
                WaterListBean.Water water= garden_waterList_adapter.getDataList().get(pos);
                Intent intent=new Intent(getActivity(),Garden_Water_Activity.class);
                intent.putExtra("water",water);
                startActivity(intent);
            }
        });

        getDatas();
    }
    private int selectIndex;

    public void onEventMainThread(PostWater postWater) {

        if (selectIndex>garden_waterList_adapter.getDataList().size())
            return;

        WaterListBean.Water  water_result= postWater.getWater();
        WaterListBean.Water  water=garden_waterList_adapter.getDataList().get(selectIndex);
        if (water_result.getWaterId().equals(water.getWaterId()))
        {

            garden_waterList_adapter.getDataList().set(selectIndex,water_result);
            garden_waterList_adapter.notifyDataSetChanged();

//            int[] st1=water_result.getSwitchsTime();
//            int[] st2=water.getSwitchsTime();
//            if (st1!=null&&st2!=null&&st1.length==st2.length)
//            {
//                for (int i=0;i<st1.length;i++)
//                {
//                    if ((st1[i]==0&&st2[i]>0)||(st1[i]>0&&st2[i]==0))
//                    {
//
//                        break;
//                    }
//                }
//            }
        }

    }

        @Override
    public void onResume() {
        super.onResume();
    }

    public void getDatas() {

        RequestParams params = new RequestParams();
        params.put("userId", Global.user.getUserId());

        if (Global.selectedArea!=null&&Global.selectedArea.getAreaId().equals("")==false)
        {
            pageNo=-1;
            params.put("areaId", Global.selectedArea.getAreaId());
            params.put("pageNo",pageNo);
            params.put("pageSize",REQUEST_COUNT);
        }
        else
        {
            params.put("pageNo", pageNo);
            params.put("pageSize",REQUEST_COUNT);
            lrv_waterList.setNoMore(false);
        }
        sPlantClient.get(sPlantAsyncHttpClient.GETWATERDEVICES, params, new sPlantJsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        try
                        {
                            if (response.getInt("succeed") == 1)
                            {
                                Gson gson = new Gson();
                                WaterListBean waterListBean = gson.fromJson(response.toString(), WaterListBean.class);
                                if (Global.selectedArea!=null)
                                    areaId=Global.selectedArea.getAreaId();

                                if (waterListBean.getWaterList() != null)
                                waterList.addAll(waterListBean.getWaterList());

                                garden_waterList_adapter.setDataList(waterList);

                                if (waterListBean.getWaterList() == null||waterListBean.getWaterList().size()<REQUEST_COUNT)
                                    lrv_waterList.setNoMore(true);

                                lrv_waterList.refreshComplete(REQUEST_COUNT);

                                if (waterList.size()==0)
                                    Toast.makeText(getActivity(),"此区域内无灌溉器",Toast.LENGTH_LONG).show();
                            }
                        }
                        catch (Exception e)
                        {
                            lrv_waterList.refreshComplete(REQUEST_COUNT);
                        }
                    }
                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                        lrv_waterList.refreshComplete(REQUEST_COUNT);
                        Toast.makeText(getActivity(), getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
                    }
                });

    }

    public void openAreaDevicesSuccess(int waterLength)
    {
        List<WaterListBean.Water> waterList=garden_waterList_adapter.getDataList();
         if (waterList!=null)
         {
             for (WaterListBean.Water water:waterList)
             {
                 int[] switchsTime=water.getSwitchsTime();
                 if (switchsTime!=null)
                 {
                     for (int i=0;i<switchsTime.length;i++)
                         switchsTime[i]=waterLength;
                 }
                 if(waterLength==0)
                     water.setOpenCloseFailure(0);
             }
             lRecyclerViewAdapter.notifyDataSetChanged();
         }
    }

    public void openAreaDevicesFailure(String failWaterIds,int waterLength)
    {
        List<WaterListBean.Water> waterList=garden_waterList_adapter.getDataList();
        if (waterList!=null)
        {
            for (WaterListBean.Water water:waterList)
            {
                if (failWaterIds.contains(water.getWaterId()))
                {
                    if (waterLength==0)
                        water.setOpenCloseFailure(2);
                    else
                        water.setOpenCloseFailure(1);
                }
                else
                {
                    int[] switchsTime=water.getSwitchsTime();
                    if (switchsTime!=null)
                    {
                        for (int i=0;i<switchsTime.length;i++)
                            switchsTime[i]=waterLength;
                    }
                }
            }
            lRecyclerViewAdapter.notifyDataSetChanged();
        }
    }

    private OnRefreshListener onRefreshListener=new OnRefreshListener() {
        @Override
        public void onRefresh() {
            pageNo=0;
            waterList.clear();
            lrv_waterList.setNoMore(false);
            getDatas();
        }
    };
    private int pageNo = 0;
    private OnLoadMoreListener onLoadMoreListener=new OnLoadMoreListener() {
        @Override
        public void onLoadMore() {
            if (pageNo>=0)
            {
                pageNo += 1;
                lrv_waterList.setNoMore(false);
                getDatas();
            }
            else
                lrv_waterList.setNoMore(true);
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
